---
import ToolButton from "./ToolButton.astro";
---
<!-- 返回顶部 -->
<ToolButton
  id="backToTop"
  tooltipText="返回顶部"
>

<svg
    xmlns="http://www.w3.org/2000/svg"
    fill="none"
    viewBox="0 0 24 24"
    stroke-width="1.5"
    stroke="currentColor"
    class="w-8 h-8 mt-2 transition-transform hover:-rotate-45"
  >
    <path
      stroke-linecap="round"
      stroke-linejoin="round"
      d="M15.59 14.37a6 6 0 0 1-5.84 7.38v-4.8m5.84-2.58a14.98 14.98 0 0 0 6.16-12.12A14.98 14.98 0 0 0 9.631 8.41m5.96 5.96a14.926 14.926 0 0 1-5.841 2.58m-.119-8.54a6 6 0 0 0-7.381 5.84h4.8m2.581-5.84a14.927 14.927 0 0 0-2.58 5.84m2.699 2.7c-.103.021-.207.041-.311.06a15.09 15.09 0 0 1-2.448-2.448 14.9 14.9 0 0 1 .06-.312m-2.24 2.39a4.493 4.493 0 0 0-1.757 4.306 4.493 4.493 0 0 0 4.306-1.758M16.5 9a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Z"
    ></path>
  </svg>
</ToolButton>

<script>
  document.getElementById("backToTop")?.addEventListener("click", function () {
    scrollToTop(window.scrollY, 0, 1000);
  });

  function easeInOutQuad(t, b, c, d) {
    t /= d / 2;
    if (t < 1) return (c / 2) * t * t + b;
    t--;
    return (-c / 2) * (t * (t - 2) - 1) + b;
  }

  function scrollToTop(start, end, duration) {
    let startTime = performance.now();

    function animate(currentTime) {
      const elapsed = currentTime - startTime;
      if (elapsed > duration) {
        // 超过设定滑动时间，停止动画
        window.scrollTo(0, end);
      } else {
        // 计算当前位置，使用easeInOutQuad缓动函数
        const newPosition = easeInOutQuad(
          elapsed,
          start,
          end - start,
          duration
        );

        // 限制滚动位置在有效范围内
        window.scrollTo(
          0,
          Math.min(Math.max(0, newPosition), document.body.scrollHeight)
        );

        // 继续动画
        requestAnimationFrame(animate);
      }
    }

    // 开始动画
    requestAnimationFrame(animate);
  }
</script>
